<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
// Models
use App\Models\Region;
use App\Models\SpecialNumber;
use App\Models\WinningLotteryNumber;
use App\Models\WinningHistory;
use App\Models\Order;
use App\Models\BetNumber;
//
use Log;

class RegionController extends Controller
{
    //
    public function getRegions()
    {
        $regions = Region::with("specialNumbers")->get();

        return response()->json(["status" => 200, "data" => $regions, "message" => "success"], 200);
    }

    public function saveRegionTimeLimit(Request $request)
    {
        $validator = Validator::make($request->all(), [
    		'id' => 'required',
    	]);

    	if ($validator->fails()) {
    		return response()->json(["status" => 400, "message" => config('messages.required_param')], 200);
        }

        $region = Region::find($request->id);
        $region->start0 = $request->start0 ? $request->start0 : $region->start0;
        $region->end0 = $request->end0 ? $request->end0 : $region->end0;
        $region->disable0 = $request->disable0;
        $region->start1 = $request->start1 ? $request->start1 : $region->start1;
        $region->end1 = $request->end1 ? $request->end1 : $region->end1;
        $region->disable1 = $request->disable1;
        $region->start2 = $request->start2 ? $request->start2 : $region->start2;
        $region->end2 = $request->end2 ? $request->end2 : $region->end2;
        $region->disable2 = $request->disable2;
        $region->start3 = $request->start3 ? $request->start3 : $region->start3;
        $region->end3 = $request->end3 ? $request->end3 : $region->end3;
        $region->disable3 = $request->disable3;
        $region->start4 = $request->start4 ? $request->start4 : $region->start4;
        $region->end4 = $request->end4 ? $request->end4 : $region->end4;
        $region->disable4 = $request->disable4;
        $region->start5 = $request->start5 ? $request->start5 : $region->start5;
        $region->end5 = $request->end5 ? $request->end5 : $region->end5;
        $region->disable5 = $request->disable5;
        $region->start6 = $request->start6 ? $request->start6 : $region->start6;
        $region->end6 = $request->end6 ? $request->end6 : $region->end6;
        $region->disable6 = $request->disable6;
        $region->digit4_limit = $request->digit4_limit ? $request->digit4_limit : $region->digit4_limit;
        $region->digit4_pool_limit = $request->digit4_pool_limit ? $request->digit4_pool_limit : $region->digit4_pool_limit;
        $region->digit3_limit = $request->digit3_limit ? $request->digit3_limit : $region->digit3_limit;
        $region->digit3_pool_limit = $request->digit3_pool_limit ? $request->digit3_pool_limit : $region->digit3_pool_limit;
        $region->digit2_limit = $request->digit2_limit ? $request->digit2_limit : $region->digit2_limit;
        $region->digit2_pool_limit = $request->digit2_pool_limit ? $request->digit2_pool_limit : $region->digit2_pool_limit;
        $region->save();

        $regions = Region::with("specialNumbers")->get();

        return response()->json(["status" => 200, "data" => $regions, "message" => "success"], 200);
    }

    public function getTodayRegionalTimeLimit() {
        $regions = Region::select("region_name", 'start' . date("w") . ' AS start', 'end' . date("w") . ' AS end', 'disable' . date("w") . ' AS disable')->get();
        return response()->json(["status" => 200, "data" => $regions, "message" => "success"], 200);
    }

    public function addSpecialNumber(Request $request)
    {
        $validator = Validator::make($request->all(), [
    		'region_id' => 'required',
    		'number' => 'required|min:2|max:5',
    		'limit' => 'required',
    	]);

    	if ($validator->fails()) {
    		return response()->json(["status" => 400, "message" => "Invalid params"], 200);
        }

        SpecialNumber::create([
            "region_id" => $request->region_id,
            "number" => $request->number,
            "limit" => $request->limit
        ]);

        $regions = Region::with("specialNumbers")->get();

        return response()->json(["status" => 200, "data" => $regions, "message" => "success"], 200);
    }

    public function deleteSpecialNumber(Request $request)
    {
        $validator = Validator::make($request->all(), [
    		'id' => 'required',
    	]);

    	if ($validator->fails()) {
    		return response()->json(["status" => 400, "message" => config('messages.required_param')], 200);
        }

        $specialNum=  SpecialNumber::find($request->id);
        if (!$specialNum) {
            return response()->json(["status" => 400, "message" => "There is no matched data."], 200);
        }
        $specialNum->delete();

        $regions = Region::with("specialNumbers")->get();

        return response()->json(["status" => 200, "data" => $regions, "message" => "success"], 200);
    }

    public function getWinningLotteryNumbers(Request $request)
    {
        //
        $startDate = $request->start ? $request->start : '';
        $endDate = $request->end ? $request->end : '';
        $data["regions"] = Region::with(['winningLotteryNumbers' => function ($query) use ($startDate, $endDate) {
                                if ($startDate) {
                                    $query->where('date', '>=', $startDate);
                                }
                                if ($endDate) {
                                    $query->where('date', '<=', $endDate);
                                }
                                $query->orderBy('date', 'DESC');
                            }])
                            ->select('id', 'region_name')
                            ->orderBy('id', 'ASC')
                            ->get();

        return response()->json(["status" => 200, "data" => $data, "message" => "success"], 200);
    }

    public function getWinningNumbersByDate(Request $request)
    {
        $validator = Validator::make($request->all(), [
    		'date' => 'required',
    	]);

    	if ($validator->fails()) {
    		return response()->json(["status" => 400, "message" => config('messages.required_param')], 200);
        }

        $regions = Region::orderBy('id', 'ASC')->get();
        $todayWinningNumbers = [];
        foreach ($regions as $region) {
            $winningLotteryNum = WinningLotteryNumber::where('region_id', $region->id)
                                                    ->whereDate('date', $request->date)
                                                    ->first();
            if (!$winningLotteryNum) {
                WinningLotteryNumber::create([
                    'region_id' => $region->id,
                    'date' => $request->date,
                    'rank1_number' => '',
                    'rank2_number' => '',
                    'rank3_number' => '',
                    'is_determined' =>false
                ]);
                array_push($todayWinningNumbers, array(
                    'id' => $region->id,
                    'region_name' => $region->region_name,
                    'date' => $request->date,
                    'rank1_number' => '',
                    'rank2_number' => '',
                    'rank3_number' => '',
                    'is_determined' =>false
                ));
            } else {
                array_push($todayWinningNumbers, array(
                    'id' => $region->id,
                    'region_name' => $region->region_name,
                    'date' => $winningLotteryNum->date,
                    'rank1_number' => $winningLotteryNum->rank1_number,
                    'rank2_number' => $winningLotteryNum->rank2_number,
                    'rank3_number' => $winningLotteryNum->rank3_number,
                    'is_determined' =>$winningLotteryNum->is_determined
                ));
            }
        }

        $data["todayWinningNumbers"] = $todayWinningNumbers;

        return response()->json(["status" => 200, "data" => $data, "message" => "success"], 200);
    }

    public function saveWinningNumbers(Request $request)
    {
        $validator = Validator::make($request->all(), [
    		'winning_numbers' => 'required',
    	]);

    	if ($validator->fails()) {
    		return response()->json(["status" => 400, "message" => config('messages.required_param')], 200);
        }

	date_default_timezone_set('America/Caracas');

	//111迭代保存
        foreach ($request->winning_numbers as $winning_number) {
            $winningNum = WinningLotteryNumber::where('date', $winning_number["date"])
                                            ->where('region_id', $winning_number["id"])
                                            ->first();
            $winningNum->rank1_number = $winning_number["rank1_number"] != null ? $winning_number["rank1_number"] : $winningNum->rank1_number;
            $winningNum->rank2_number = $winning_number["rank2_number"] != null ? $winning_number["rank2_number"] : $winningNum->rank2_number;
            $winningNum->rank3_number = $winning_number["rank3_number"] != null ? $winning_number["rank3_number"] : $winningNum->rank3_number;
            $winningNum->is_determined = ($winning_number["rank1_number"] != '') && ($winning_number["rank2_number"] != '') && ($winning_number["rank3_number"] != '');
            $winningNum->checked_winning = 0;
            $winningNum->save();
        }

	$today = date('Y-m-d');
    $tomorrow = date('Y-m-d', strtotime("+1 day"));
	//$today = date('Y-m-d', strtotime('-4 hour'));
        // clear the old prizes today
        $winningHistory = WinningHistory::where('created_at', '>=', $today . ' 04:00:00')
                                        ->where('created_at', '<=', $tomorrow . ' 03:59:59')
                                        ->get();
        foreach ($winningHistory as $row) {
            $_row = WinningHistory::find($row->id);
            if($_row) {
                $_row->delete();
            }
        }//////////
        $betNums = BetNumber::whereHas('order', function($query) {
                                $query->where('is_deleted', false);
                            })
                            ->where('created_at', '>=', $today . ' 04:00:00')
                            ->where('created_at', '<=', $tomorrow . ' 03:59:59')
                            ->get();
        foreach ($betNums as $betNum) {
            $_betNum = BetNumber::find($betNum->id);
            if($_betNum) {
                $_betNum->is_winner = 0;
                $_betNum->rank = 0;
                $_betNum->prizes = 0;
                $_betNum->save();
            }
        }

        //
        $orders = Order::where('created_at', '>=', $today . ' 04:00:00')
                        ->where('created_at', '<=', $tomorrow . ' 03:59:59')
                        ->where('is_deleted', false)
                        ->get();
        foreach ($orders as $order) {
            $_order = Order::find($order->id);
            if($_order) {
                $_order->is_winner = 0;
                $_order->total_winning_amount = 0;
                $_order->save();
            }
        }

	// recalculate the prizes today
	//date_default_timezone_set('America/Caracas');
        $regions = Region::orderBy('id', 'ASC')->get();


	foreach($regions as $region) {
            //
        $end_time = $region['end' . date("w")];
	    $end_at = $today . ' ' .  $end_time;

//        return response()->json(["status" => 200, "data" => $end_at, "message" => "success"], 200);

	    //echo $end_at.'   '.date('Y-m-d H:i:s');die;
	    Log::info('当前时间: ' . date('Y-m-d H:i:s').'===取出的字段时间: '.$end_at. '===传入参数: '.json_encode($request->winning_numbers));
            if (date('Y-m-d H:i:s') > $end_at) {
                determinePrizesToWinningNumbers($region, $today);
                Log::info('==== Redetermined Winning Prizes - Date: ==== ' . date('Y-m-d H:i:s'));
            }
        }

        return response()->json(["status" => 200, "data" => "", "message" => "success"], 200);
    }


    // ================== App Api ==================== //
    public function getWinningLotteryNumbersByDate(Request $request)
    {
        //
        $validator = Validator::make($request->all(), [
    		'date' => 'required',
    	]);

    	if ($validator->fails()) {
    		return response()->json(["status" => 400, "message" => config('messages.required_param')], 200);
        }

        $date = $request->date;
        $data = $this->getWinningLotteryNumbersByDateFunc($date);

        return response()->json(["status" => 200, "data" => $data, "message" => "success"], 200);
    }

    private function getWinningLotteryNumbersByDateFunc($date) {
        $today = date('Y-m-d');

        $regions = Region::orderBy('id', 'ASC')->get();
        $winningNumbers = [];
        foreach ($regions as $region) {
            $winningLotteryNum = WinningLotteryNumber::where('region_id', $region->id)
                                                    ->whereDate('date', $date)
                                                    ->first();
            if (!$winningLotteryNum && $date <= $today) {
                WinningLotteryNumber::create([
                    'region_id' => $region->id,
                    'date' => $date,
                    'rank1_number' => '',
                    'rank2_number' => '',
                    'rank3_number' => '',
                ]);
                array_push($winningNumbers, array(
                    'id' => $region->id,
                    'region_name' => $region->region_name,
                    'date' => $date,
                    'rank1_number' => '',
                    'rank2_number' => '',
                    'rank3_number' => '',
                ));
            } else if ($winningLotteryNum) {
                array_push($winningNumbers, array(
                    'id' => $region->id,
                    'region_name' => $region->region_name,
                    'date' => $winningLotteryNum->date,
                    'rank1_number' => $winningLotteryNum->rank1_number,
                    'rank2_number' => $winningLotteryNum->rank2_number,
                    'rank3_number' => $winningLotteryNum->rank3_number,
                ));
            }
        }
        $data["date"] = $date;
        $data["winningNumbers"] = $winningNumbers;

        return $data;
    }

    public function getWinningLotteryNumbersOfLast7Days(Request $request)
    {
        //
        $startDate = date('Y-m-d', strtotime('-7 days'));
        $endDate = date('Y-m-d');
        $data = [];
        for ($i = 0; $i < 7; $i++) {
            $date = date('Y-m-d', strtotime('-' . $i . ' days'));
            $dataByDate = $this->getWinningLotteryNumbersByDateFunc($date);
            array_push($data, $dataByDate);
        }

        return response()->json(["status" => 200, "data" => $data, "message" => "success"], 200);
    }
}
